import 'package:flutter/widgets.dart';
import 'package:flutter_app/tools/http.dart';
import 'package:flutter_app/model/news.dart';
import 'package:flutter_app/view/news/news_grid_item.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/common/global.dart';
import 'package:flutter_app/tools/utils.dart';
import 'package:flutter_app/tools/widget.dart';
// import 'package:pull_to_refresh/pull_to_refresh.dart';

class NewsListView extends StatefulWidget {
  NewsListView({Key key}) : super(key: key);

  @override
  _NewsListViewState createState() => _NewsListViewState();
}

class _NewsListViewState extends State<NewsListView>
    with AutomaticKeepAliveClientMixin {
  int p = 0; //
  String refreshTime; //刷新时间
  List<News> newsList = [];
  bool noMore = false; //没有更多

  bool isLoading = false; //是否正在加载数据

  ScrollController _controller = new ScrollController(); //上拉加载更多控制器

  GlobalKey<RefreshIndicatorState> _indicatorKey =
      GlobalKey<RefreshIndicatorState>(); //下拉刷新控件

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    _onRefresh();
  }

//获取新闻列表根据页号
  getNewsList() async {
    if (!isLoading) {
      isLoading = true;
      p += 1;
      if (p == 1) {
        newsList = [];
        refreshTime = m_utils.formartDateTimeToSecond(DateTime.now());
        noMore = false;
      }
      if (!noMore) {
        final lb = await Global.loadBalancer;
        List<News> resultList = await lb.run<List<News>, Map<String, dynamic>>(
            m_http.getNewsList, {"p": p, "refreshTime": refreshTime});
        if (resultList.length > 0) {
          newsList.addAll(resultList);
        } else {
          noMore = true;
        }
      }
      isLoading = false;
    }
    setState(() {});
  }

  //下拉重新刷新
  Future<Null> _onRefresh() async {
    p = 0;
    await getNewsList();
    await Future.delayed(Duration(milliseconds: 2000), () {});
  }

  Widget getRow([News news]) {
    return NewsGridItem(
      news: news,
      key: UniqueKey(), //必须要有key 不然setState时listView可能不刷新
    );
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Stack(children: [
      RefreshIndicator(
        key: _indicatorKey,
        child: ListView.builder(
          scrollDirection: Axis.vertical,
          physics: const AlwaysScrollableScrollPhysics(),
          cacheExtent: 0,
          itemCount: newsList.length + 1,
          itemBuilder: (BuildContext context, int position) {
            if (position < newsList.length) {
              return getRow(newsList[position]);
            } else {
              if (_controller.position.haveDimensions &&
                  !_controller.position.outOfRange &&
                  !noMore) {
                Future.delayed(Duration(milliseconds: 200)).then((e) {
                  getNewsList();
                });
              }
              return utilsWidget.loadingWidget(isLoading, noMore);
            }
          },
          controller: _controller,
        ),
        onRefresh: _onRefresh,
      ),
      Positioned(
        right: 30,
        bottom: 75,
        child: Container(
            width: 30,
            height: 30,
            child: Align(
              child: FloatingActionButton(
                tooltip: '刷新', // used by assistive technologies
                heroTag: "刷新新闻",
                child: Icon(
                  Icons.refresh,
                  size: 25.0,
                ),

                onPressed: () {
                  // getTweetList();
                  //_indicatorKey.currentState.show();
                  if (_controller.position.pixels > 0) {
                    _controller.jumpTo(0);
                  } else {
                    _indicatorKey.currentState.show();
                  }
                },
              ),
            )),
      )
    ]);
  }
}
